package com.example.x50;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;

import com.example.x50.untils.Convert;

import java.io.IOException;
import java.lang.reflect.Array;

import cn.hutool.core.io.BufferUtil;

public class FirstFragment extends Fragment {
    TextView textView;
    @Override
    public View onCreateView(
            LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_first, container, false);
    }
    private Handler handler = new Handler(new Handler.Callback() {
        //消息处理方法
        @Override
        public boolean handleMessage(@NonNull Message msg) {

            Log.e("接收数据", Convert.BinaryToHexString((byte[]) msg.obj));
            textView.setText( Convert.BinaryToHexString((byte[]) msg.obj));
            return false;
        }
    });
    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        textView=view.findViewById(R.id.textview_first);


        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        //拿到主线程Handler的Message
                        Message msg = handler.obtainMessage();
                        //将进度值作为消息的参数包装进去，进度自加1
                        msg.obj = UdpServer.rec(8080);
                        //将消息发送给主线程的Handler
                        handler.sendMessage(msg);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
           }
                }
        }).start();
        super.onViewCreated(view, savedInstanceState);
//        new Thread(new TcpServer(8899)).start();
        view.findViewById(R.id.button_first).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                textView.setText("1");
            }
        });
    }
}